<template>
  <div id="qidatabaseDiv">
    <Breadcrumb content="数据源配置" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findQiDatabaseList" @keyup="keyupEnter" @search-click="findQiDatabaseList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" @click="findQiDatabaseList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addQiDatabaseDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteQiDatabase"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="databaseTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="left" height="auto" :data="databaseList" :loading="iloading" @current-change="databaseRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="seq" title="序号" width="50"></vxe-column>
              <vxe-column field="databaseCode" title="数据源编码" width="100"></vxe-column>
              <vxe-column field="databaseName" title="数据源名称" width="200"> </vxe-column>
              <vxe-column field="dbType" title="数据库类型" width="100">
                <template #default="{ row }">
                  <span>{{ formatCommon(dbMsList, row.dbType) }}</span>
                </template>
              </vxe-column>

              <vxe-column field="dbName" title="数据库名称" width="130"> </vxe-column>
              <vxe-column field="dbUrl" title="数据库地址" width="100"> </vxe-column>
              <vxe-column field="port" title="端口" width="100"> </vxe-column>
              <vxe-column field="dbUser" title="用户名" width="100"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <el-scrollbar style="height: 100%">
                <el-form ref="databaseFormRef" :model="databaseForm" :rules="databaseFormRule" label-width="120px" inline-message>
                  <el-row :gutter='20'>
                    <el-col :span='12'>
                  <el-form-item prop="databaseCode" label="数据源编码">
                    <el-input type="text" v-model="databaseForm.databaseCode" placeholder="请输入数据源编码" clearable></el-input>
                  </el-form-item>
                </el-col>
               </el-row>

               <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item prop="databaseName" label="数据源名称">
                    <el-input type="text" v-model="databaseForm.databaseName" placeholder="请输入数据源名称" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item prop="dbType" label="数据库类型">
                    <el-select v-model="databaseForm.dbType" placeholder="请选择">
                      <el-option v-for="item in dbMsList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item prop="dbName" label="数据库名称">
                    <el-input type="text" v-model="databaseForm.dbName" placeholder="请输入" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item prop="dbUrl" label="数据库地址">
                    <el-input type="text" v-model="databaseForm.dbUrl" placeholder="请输入" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item prop="dbUser" label="登录帐户">
                    <el-input type="text" v-model="databaseForm.dbUser" placeholder="请输入" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item prop="dbPass" label="帐户密码">
                    <el-input type="text" v-model="databaseForm.dbPass" placeholder="请输入" show-password></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item label="端口" prop="port">
                    <el-input type="text" v-model="databaseForm.port" placeholder="端口" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="databaseForm.remark" :rows="6" type="textarea" placeholder="备注" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter='20'>
                <el-col :span='12'>
                  <el-form-item prop="seq" label="序号">
                    <el-input-number v-model="databaseForm.seq" :min="1" :max="1000" />
                  </el-form-item>
                </el-col>
              </el-row>

                  <el-form-item class="form-footer">
                    <template #default>
                      <el-button type="primary" :loading="saveLoading" @click="saveDatabase('databaseFormRef')">保存</el-button>
                      <el-button type="primary" :loading="testConnectionLoading" @click="testConnection()">测试连接</el-button>

                    </template>
                  </el-form-item>

                </el-form>
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区==========
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';

// 全局变量定义区 ==========
let store = AppStore();
let iloading = ref(false); //加载状态
let saveLoading = ref(false); //表单保存状态
let testConnectionLoading = ref(false); //表单保存状态
let sltDatabase: any = reactive({});
let databaseList: any = reactive([]);
let dbMsList: any = reactive([]); //选择字典

let searchForm = reactive({ searchValue: '' });

let databaseForm = reactive({
  id: null,
  databaseName: '',
  databaseCode: '',
  dbType: '',
  dbName: '',
  dbUrl: '',
  port: '',
  dbUser: '',
  dbPass: '',
  remark: '',
  seq: 1,
  orgId: ''
});

let databaseFormRule = {
  databaseCode: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  databaseName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ]
};

onMounted(() => {
  getDictItemsList();
  findQiDatabaseList();
});
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['dbMsType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const dbMsType = dictTreeTypeItems.data.find((item) => item.code === 'dbMsType');
  dbMsList.push(...dbMsType.detailDataList);
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findQiDatabaseList();
  }
}

function findQiDatabaseList() {
  iloading.value = true;
  databaseList.length = 0; //放入数据前清空数据
  const url = '/api/qi/qiDatabase/findQiDatabaseList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue
      }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        databaseList.push(...res.data);
        iloading.value = false;
        const kn = databaseList.find((k) => k.id == sltDatabase.id);
        if (isEmpty(kn)) {
          databaseRowClick({ row: databaseList[0] }); //默认选中第一条数据
        } else {
          databaseRowClick({ row: kn }); //默认选中第一条数据
        }
      } else {
        iloading.value = false;
        VxeMessage('获取列表失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      iloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function databaseRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearForm();
  } else {
    (proxy.$refs.databaseTableRef as any).setCurrentRow(row);
    setDatabaseForm(row);
  }
}
function addQiDatabaseDialog() {
  clearForm();
}

function saveDatabase(formName: any) {
  let $el = proxy.$refs[formName];

  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    saveLoading.value = true;

    let url = '';
    let objData = {
      id: databaseForm.id,
      databaseName: databaseForm.databaseName,
      databaseCode: databaseForm.databaseCode,
      dbType: databaseForm.dbType,
      dbName: databaseForm.dbName,
      dbUrl: databaseForm.dbUrl,
      port: databaseForm.port,
      dbUser: databaseForm.dbUser,
      dbPass: databaseForm.dbPass,
      remark: databaseForm.remark,
      seq: databaseForm.seq,
      orgId: isEmpty(databaseForm.orgId) ? store.userInfo.orgId : databaseForm.orgId
    };
    if (databaseForm.id == null) {
      url = '/api/qi/qiDatabase/addDatabase';
    } else {
      url = '/api/qi/qiDatabase/editDatabase';
    }

    proxy.$http
      .post(url, objData)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          clearForm();
          sltDatabase.id = res.data.id;
          findQiDatabaseList();
        } else {
          VxeMessage('保存失败1', VxeNotifyType.error);
        }
        saveLoading.value = false;
      })
      .catch((err: any) => {
        saveLoading.value = false;
        VxeMessage('保存失败2', VxeNotifyType.error);
      });
  });
}

function deleteQiDatabase() {
  const sltDatabases = (proxy.$refs.databaseTableRef as any).getCheckboxRecords();
  if (!(sltDatabases.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { databaseList: sltDatabases };
        const url = '/api/qi/qiDatabase/batchDeleteDatabaseList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            if (res.status.code === 1) {
              findQiDatabaseList(); // 获取检验仪器表格数据
              VxeMessage('删除成功', VxeNotifyType.success);
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 测试数据库连接
function testConnection() {
  testConnectionLoading.value = true;
  let url = '/api/qi/qiDatabase/qiDatabaseConnection';
  const el: any = proxy.$refs.databaseFormRef;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      testConnectionLoading.value = false;
      return false;
    }
    proxy.$http
      .post(url, databaseForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        testConnectionLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        testConnectionLoading.value = false;
      });
  });
}

function clearForm() {
  databaseForm.id = null;
  databaseForm.databaseName = '';
  databaseForm.databaseCode = '';
  databaseForm.dbType = '';
  databaseForm.dbName = '';
  databaseForm.dbUrl = '';
  databaseForm.port = '';
  databaseForm.dbUser = '';
  databaseForm.dbPass = '';
  databaseForm.remark = '';

  databaseForm.seq = databaseList.length + 1;
  databaseForm.orgId = '';
  sltDatabase = {};
}

function setDatabaseForm(row: any) {
  databaseForm.id = row.id;
  databaseForm.databaseName = row.databaseName;
  databaseForm.databaseCode = row.databaseCode;
  databaseForm.dbType = row.dbType;
  databaseForm.dbName = row.dbName;
  databaseForm.dbUrl = row.dbUrl;
  databaseForm.port = row.port;
  databaseForm.dbUser = row.dbUser;
  databaseForm.dbPass = row.dbPass;
  databaseForm.remark = row.remark;
  databaseForm.seq = row.seq;
  databaseForm.orgId = row.orgId;
  sltDatabase = row;
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>

<style lang="scss" scoped>
#qidatabaseDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);
          .el-tab-pane {
            height: 100%;
          }
          #pane-0 {
            .el-form {
              padding: 15px;
              height: calc(100% - 30px);
            }
          }
        }
      }
      // 各个组件与右侧删除按钮的间距
      .vxe-checkbox {
        margin: 5px;
      }
    }
  }
}
</style>
